package lv.solcraft.replication.server.dao;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.bdb.Database.OperSiteStore;
import lv.solcraft.replication.server.model.OperId;
import lv.solcraft.replication.server.model.OperSite;
import lv.solcraft.replication.server.model.Record;

import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.SecondaryIndex;

public class OperSiteDataAccess extends BaseDataAccess<OperId, OperSite> {

    private final SecondaryIndex<Record, OperId, OperSite> recordIndex;
    private OperSiteDataAccessFactory operSiteDataAccessFactory;
    private OperDataAccess operDataAccess;
    private OperSiteStore operSiteStore;

    public OperSiteDataAccess(OperSiteStore store, Database database) {
        super(store.getEntityStore(), database, OperId.class, OperSite.class);
        this.operSiteStore = store;
        this.operDataAccess = database.getOperDataAccess();
        this.operSiteDataAccessFactory = database.getOperSiteDataAccessFactory();
        try {
            recordIndex = this.store.getSecondaryIndex(primary, Record.class, "record");
        } catch (DatabaseException e) {
            throw new DataAccessException("Could not create index by record", e);
        }
    }

    public boolean contains(Record record) {
        try {
            return recordIndex.get(database.activeTx(), record, LockMode.READ_COMMITTED) != null;
        } catch (DatabaseException e) {
            throw new DataAccessException("Error while checking if oper site store contans record " + record, e);
        }
    }

    public EntityCursor<OperSite> cursor() throws DatabaseException {
        return primary.entities(database.activeTx(), null);
    }

    @Override
    protected OperSite afterRead(OperSite entity) {
        if (entity == null)
            return null;
        entity.inject(operDataAccess, operSiteDataAccessFactory);
        return entity;
    }
}